﻿@namespace BootstrapBlazor.Components
@using Microsoft.AspNetCore.Components.Web.Virtualization
@typeparam TValue
@inherits PopoverCompleteBase<TValue>

@if (IsShowLabel)
{
    <BootstrapLabel required="@Required" for="@InputId" ShowLabelTooltip="ShowLabelTooltip" Value="@DisplayText" />
}
<div class="@ClassString" id="@Id">
    <input @attributes="AdditionalAttributes" id="@InputId" class="@ClassName" autocomplete="off" type="text"
           data-bs-toggle="@ToggleString" data-bs-placement="@PlacementString"
           data-bs-offset="@OffsetString" data-bs-custom-class="@CustomClassString"
           data-bb-auto-dropdown-focus="@ShowDropdownListOnFocusString" data-bb-debounce="@DurationString"
           data-bb-skip-esc="@SkipEscString" data-bb-skip-enter="@SkipEnterString" data-bb-blur="@TriggerBlurString"
           data-bb-scroll-behavior="@ScrollIntoViewBehaviorString"
           placeholder="@PlaceHolder" disabled="@Disabled" />
    <span class="form-select-append"><i class="@Icon"></i></span>
    <span class="form-select-append ac-loading"><i class="@LoadingIcon"></i></span>
    @if (GetClearable())
    {
        <span class="@ClearClassString"><i class="@ClearIcon"></i></span>
    }
    <RenderTemplate @ref="_dropdown">
        @RenderDropdown
    </RenderTemplate>
</div>

@code {
    RenderFragment RenderDropdown =>
    @<div class="dropdown-menu">
        @if (IsVirtualize)
        {
            <div class="dropdown-menu-body dropdown-virtual">
                @if (OnQueryAsync == null)
                {
                    <Virtualize ItemSize="RowHeight" OverscanCount="OverscanCount" Items="@Rows" ChildContent="RenderRow">
                    </Virtualize>
                }
                else
                {
                    <Virtualize ItemSize="RowHeight" OverscanCount="OverscanCount" ItemsProvider="LoadItems"
                                Placeholder="RenderPlaceholderRow" ItemContent="RenderRow" @ref="_virtualizeElement">
                    </Virtualize>
                }
            </div>
        }
        else if (ShowNoDataTip && Rows.Count == 0)
        {
            <div class="dropdown-item">@NoDataTip</div>
        }
        else
        {
            <div class="dropdown-menu-body">
                @foreach (var item in Rows)
                {
                    @RenderRow(item)
                }
            </div>
        }
    </div>;

    RenderFragment<TValue> RenderRow => item =>
    @<div @key="@item" class="dropdown-item" @onclick="() => OnClickItem(item)">
        @if (ItemTemplate != null)
        {
            @ItemTemplate(item)
        }
        else
        {
            <div>@GetDisplayText(item)</div>
        }
    </div>;

    RenderFragment<PlaceholderContext> RenderPlaceholderRow => context =>
    @<div class="dropdown-item" style="@PlaceHolderStyleString">
        <div class="is-ph"></div>
    </div>;
}
